<template>
  <ul
    class="com-viewer"
    v-if="images.length > 0"
    id="viewer-images">
    <li>
      <img
        class="image"
        v-for="v in images"
        :key="v"
        :src="v">
    </li>
  </ul>
</template>

<script>
  import 'viewerjs/dist/viewer.min.css'
  import { UrlClearFormat } from 'yb-tool'
  import Viewer from 'viewerjs'

  /**
   * 图片查看器
   */
  export default {
    name: "ConViewer",
    data() {
      return {
        /**
         * 图片链接数组
         */
        images: [],
        /**
         * 图片显示器对象
         */
        viewer: null
      }
    },
    methods: {
      /**
       * 显示图片查看器
       * @param images 图片链接数组
       * @param index 显示索引 默认0
       */
      show(images, index = 0) {
        let imageUrls = images

        if (typeof images === 'string') {
          imageUrls = [imageUrls]
        }
        this.images = imageUrls.map((url) => {
          return UrlClearFormat(url)
        })
        this.$nextTick(() => {
          this.viewer = new Viewer(document.getElementById('viewer-images'), {
            hidden: () => {
              this.close()
            }
          })
          this.viewer.show(index)
        })
      },
      /**
       * 关闭图片查看器
       */
      close() {
        this.viewer = null
        this.images = []
      }
    }
  }
</script>

<style lang="scss" scoped>
  .com-viewer {
    width: 0;
    height: 0;
    list-style: none;
    overflow: hidden;
  }
</style>
